/**
 * Created by root on 2017-08-14.
 */
import React, { Component, PropTypes } from 'react';
import { Utility, GxSearchBar, GxIcon, TaskList, Refresh, ApiInfo, GxButton } from 'components';
import { connect } from 'react-redux';
import * as CommonActions from 'redux/modules/reduxCommon';

@connect(
  state => ({
    Title: state.Common.Title,                                          // 标题
    UrlParams: state.Common.UrlParams,                                  // URL参数
    SearchTaskListData: state.Common.SearchTaskListData,                // 搜索活动列表
    HistoryListData: state.Common.HistoryListData,                      // 历史记录
    TaskAssignCondition: state.Common.TaskAssignCondition,              // 任务分配搜索条件
  }),
  { ...CommonActions })

export default class SearchPage extends Component {
  static propTypes = {
    Title: PropTypes.string,                                            // 标题
    UrlParams: PropTypes.object,                                        // url 参数
    SearchTaskListData: PropTypes.object,                               // 搜索结果
    TaskAssignCondition: PropTypes.object,                              // 任务分配搜索条件
    HistoryListData: PropTypes.array,                                   // 历史记录
    onApiGet: PropTypes.func,                                           // Get请求
    onUpdateRedux: PropTypes.func,                                      // 更新Redux
    onSetContent: PropTypes.func,                                       // 保存内容
    onClearContent: PropTypes.func,                                     // clear content
  };

  constructor(props) {
    super(props);
    this.state = {
      __Index: 0,
      RefreshComplete: true, NextDataComplete: true,
      IsScreen: false,                                                   // 是否显示筛选
      IsHistory: false,                                                  // 是否历史记录
      IsNotData: false,                                                  // 判断有无数据
      IsCondition: false,                                                // 确认后是否展示筛选条件
      IsBuy: false,                                                      // 是否搜索
      IsFocus: false,                                                    // 是否聚焦
      TaskLists: [],                                                     // 处理之后的任务列表
      AnTeList: [                                                        // @列表
        { Ante: '我@的', type: 'wo@' },
        { Ante: '@我的', type: '@wo' },
      ],
      CurrentSelect: 0,                                                  // 当前选中的
      Type: 'wo@',                                                       // 类型
      IsAnteWo: true,                                                    // 是否安特我
      MainStatus: [                                                      // 主状态
        { id: '01', status: 'START', title: '未处理' },
        { id: '02', status: 'RECEIVED', title: '进行中' },
        // { id: 'refuse', status: 'REFUSE', title: '已拒绝' },
        // { id: 'finished', status: 'FINISHED', title: '已完成' },
        { id: '03', status: 'OVER', title: '已关闭' },
      ],
      SubStatus: [                                                       // 子状态
        { id: '01', status: 'START', title: '未处理' },
        { id: '02', status: 'RECEIVED', title: '进行中' },
        { id: '03', status: 'REFUSE', title: '已拒绝' },
        { id: '04', status: 'FINISHED', title: '已完成' },
      ],
      CurrentSelectInfo: {},                                             // 当前选中的状态
      StatusArr: [],                                                     // 状态集合
    };
    const SearchItems = [
      { content: '历史记录' },
    ];
    this.state.SearchItems = SearchItems;
    const __ScreenCondition = [];                                       // 筛选条件集合
    __ScreenCondition[0] = this.state.CurrentSelect === 0 ? '我@的' : '@我的';
    this.state.ScreenCondition = __ScreenCondition;
  }

  componentWillMount() {
    const { UrlParams } = this.props;
    const { type } = UrlParams || {};
    const _type = Number(type);
    if (_type === 0) {
      this.state.IsFocus = false;
      this.state.IsScreen = true;
    } else if (_type === 1) {
      this.state.IsFocus = true;
      this.state.IsHistory = true;
      this.__HistoryData();
      if (Utility.$isIOS()) {
        const { searchBar } = this.refs;
        if (!searchBar) {
          return;
        }
        setTimeout(() => {
          searchBar.__SetFocus();
        }, 0);
      }
    }
    this.__UpdateRender();
  }

  componentDidMount() {
    this.state.IsMount = true;
    const { TaskAssignCondition } = this.props;
    if (TaskAssignCondition) {
      this.state.IsScreen = false;
      this.state.IsHistory = false;
      setTimeout(() => {
        this.__CallBackData(TaskAssignCondition);
      }, 1000);
    }
    this.__UpdateRender();
  }

  componentWillUnmount() {
    delete this.state.IsMount;
    // const { onClearContent } = this.props;
    // onClearContent('TaskAssignCondition');
  }

  __CallBackData(data) {
    const { userName, type, key_word } = data || {};
    const { searchBar } = this.refs;
    if (userName || type) {
      // this.state.Title = userName;
      searchBar.__GetValue(userName);
      this.__InitData(data, false);
    } else if (key_word) {
      this.__HandlerSearch(key_word);
    }
  }

  /**
   * 历史记录
   * 
   * @returns 
   * @memberof SearchPage
   */
  __HistoryData() {
    const { onApiGet } = this.props;
    const { SearchItems } = this.state;
    if (!Utility.isFunction(onApiGet)) {
      return;
    }
    this.__UpdateRender();
    Utility.$loading();
    const __self = this;
    // onClearContent('TaskAssignCondition');
    onApiGet('HistoryListData', ApiInfo.Task.HistoryList, { params: {} }).then((data) => {
      if (!Utility.isArray(data)) {
        __self.state.IsHistory = false;
      }
      const _data = SearchItems.concat(data) || [];
      __self.state.SearchItems = _data;
      __self.__UpdateRender();
      Utility.$loadingHide();
    }, (error) => {
      if (error) {
        __self.state.IsHistory = false;
      }
      __self.__UpdateRender();

      Utility.$loadingHide();
    });
  }

  /**
   * 筛选确认---接口数据
   * @returns 
   * @memberof GmessageView
   */
  __InitData(condition, isNextData) {
    const { onApiGet, SearchTaskListData, onSetContent } = this.props;
    // const { ScreenCondition } = this.state;
    if (!Utility.isFunction(onApiGet)) {
      return;
    }
    const __params = Object.assign({}, Utility.$getInitPageTurning(), condition || {});
    const __self = this;
    const __ApiList = [];
    const { List } = SearchTaskListData || {};
    if (document.body.scrollTop === 0 || !Utility.isArray(List) || !!isNextData) {
      __ApiList.push(onApiGet('SearchTaskListData', ApiInfo.Task.TaskLists, { params: __params }));
    }
    Utility.$loading();
    onSetContent('TaskAssignCondition', condition);
    Promise.all(__ApiList).then(() => {
      __self.state.CurrentSelectInfo = {};
      // __self.state.ScreenCondition = ScreenCondition.slice(0, 1);

      __self.state.StatusArr = [];
      // onClearContent('TaskAssignCondition');
      __self.__TaskListData();
      __self.__JudgeIsExistData();
      __self.state.RefreshComplete = true;
      __self.state.NextDataComplete = true;
      __self.__UpdateRender();
      Utility.$loadingHide();
    }).catch((ex) => {
      __self.__JudgeIsExistData();
      __self.state.RefreshComplete = true;
      __self.state.NextDataComplete = true;
      __self.__UpdateRender();
      Utility.$loadingHide();
      console.log(ex);
    });
  }

  /**
   * 搜索事件
   * 
   * @param {any} key 
   * @returns 
   * @memberof SearchPage
   */
  __HandlerSearch(key) {
    this.state.KeyWord = key;
    const { onApiGet, SearchTaskListData, onSetContent } = this.props;
    const search = {};
    if (key) {
      search.key_word = key;
    }
    onSetContent('TaskAssignCondition', search);
    const { IsBuy } = this.state;
    if (!Utility.isFunction(onApiGet)) {
      return;
    }
    if (!key || key === '') {
      return;
    }
    this.state.IsHistory = false;
    this.__UpdateRender();
    const __search = {};
    __search.pg_index = 0;
    __search.key_word = encodeURIComponent(this.state.KeyWord);
    __search.pg_count = Utility.constItem.PageSize;
    const __ApiList = [];
    const { List } = SearchTaskListData || {};
    this.state.RefreshComplete = false;
    if (document.body.scrollTop === 0 || !Utility.isArray(List)) {
      __ApiList.push(onApiGet('SearchTaskListData', ApiInfo.Task.TaskLists, { params: __search }));
    }
    if (!!IsBuy) {
      Utility.$actionSheet('正在处理中,请稍后...');
      return;
    }
    this.state.IsBuy = true;
    const __self = this;
    Promise.all(__ApiList).then(() => {
      __self.state.IsHistory = false;
      __self.state.IsBuy = false;
      __self.__TaskListData();
      __self.__JudgeIsExistData();
      __self.state.RefreshComplete = true;
      __self.__UpdateRender();
    }).catch((ex) => {
      __self.__JudgeIsExistData();
      __self.state.IsBuy = false;
      __self.state.RefreshComplete = true;
      __self.__UpdateRender();
      console.log(ex);
    });
    // this.__HandlerRefreshData();
  }

  /**
   * 判断有无数据列表
   * 
   * @returns 
   * @memberof GmessageView
   */
  __JudgeIsExistData() {
    const { SearchTaskListData } = this.props;
    if (SearchTaskListData && !Utility.isArray(SearchTaskListData.List)) {
      this.state.IsNotData = true;
    } else {
      this.state.IsNotData = false;
    }
    this.__UpdateRender();
  }

  /**
   * 上拉加载
   * @memberof GmessageView
   */
  __HandlerNextData() {
    const { SearchTaskListData } = this.props;
    const { Condition } = SearchTaskListData;
    const { IsExistsNextData } = Condition;
    if (!IsExistsNextData) {
      return;
    }
    this.state.NextDataComplete = false;
    this.__InitData(Condition, true);
  }

  /**
   * 下拉刷新
   * @memberof GmessageView
   */
  __HandlerRefreshData() {
    const { UrlParams } = this.props;
    const { Type, StatusArr } = this.state;
    if (this.state.KeyWord === '' || Type === '' || !Utility.isArray(StatusArr)) {
      return;
    }
    const { type } = UrlParams || {};
    const _type = Number(type);
    const __params = Object.assign({ type: Type, status: StatusArr }, Utility.$getInitPageTurning());
    const __search = Object.assign({ key_word: this.state.KeyWord }, Utility.$getInitPageTurning());
    const __condition = _type === 0 ? __params : __search;
    this.state.RefreshComplete = false;
    this.__InitData(__condition, false);
  }

  /**
   * 更新渲染
   */
  __UpdateRender() {
    if (!!this.state.IsMount) {
      this.setState({ __CurrentTempDate: new Date().getTime() });
    }
  }

  /**
   * 更新state
   * 
   * @param {any} type 
   * @memberof SearchPage
   */
  __UpdateState(type) {
    if (type) {
      this.state[type] = !this.state[type];
    }
    this.__UpdateRender();
  }

  /**
   * 页面跳转。
   * @param params
   * @private SearchPage
   */
  __HandlerGoToPage(url, params) {
    Utility.toPage(url, params);
  }

  /**
   * 搜索取消
   * 
   * @memberof GmessageDealt
   */
  __Cancel() {
    // console.log('取消');
    Utility.$goBack();
  }

  /**
   * 点击搜索栏-筛选事件
   * 
   * @memberof SearchPage
   */
  __HandlerScreen() {
    const { IsScreen } = this.state;
    this.state.IsScreen = !IsScreen;
    this.state.IsHistory = false;
    this.state.IsCondition = false;
    this.state.CurrentSelectInfo = {};
    const __ScreenCondition = [];     // 筛选条件集合
    __ScreenCondition[0] = this.state.CurrentSelect === 0 ? '我@的' : '@我的';
    this.state.ScreenCondition = __ScreenCondition;
    this.__UpdateRender();
  }

  /**
   * 历史记录
   * 
   * @param {any} styles 
   * @returns 
   * @memberof SearchPage
   */
  __SearchHistoryHtml(styles) {
    const { SearchItems } = this.state;
    // const { HistoryListData } = this.props;
    if (!Utility.isArray(SearchItems)) {
      return null;
    }
    // const _content = decodeURIComponent(content || '');
    return (
      <div className={styles.historyContainer}>
        {
          SearchItems.map((item, index) => {
            const { content } = item || {};
            return (<div className={styles.historyCss} key={'item_history' + index} onClick={this.__HandlerClickHistory.bind(this, item, index)}>
              <div className={styles.historyItem + ' ' + (index === 0 ? styles.history : '')}>
                {content}
              </div>
            </div>);
          })
        }
      </div>
    );
  }

  /**
   * 选中历史记录-筛选任务列表
   * 
   * @param {any} item 
   * @param {any} index 
   * @returns 
   * @memberof SearchPage
   */
  __HandlerClickHistory(item, index) {
    if (!item) {
      return;
    }
    if (index === 0) {
      // console.log('请点击下方的历史记录');
      return;
    }
    const { content } = item || {};
    this.state.IsHistory = false;
    const { searchBar } = this.refs;
    if (searchBar) {
      searchBar.__GetValue(content);
    }
    // this.state.Title = content;
    this.__HandlerSearch(content);
    this.__UpdateRender();
  }

  /**
   * 按照年月树状结构处理数据
   * 
   * @returns 每个月对应的数据集合 
   * @memberof TaskList
   */
  __TaskListData() {
    const { SearchTaskListData } = this.props;
    const { List } = SearchTaskListData || {};
    const TaskLists = List || [];
    if (!Utility.isArray(TaskLists)) {
      return;
    }
    const monthOfYear = ['12月', '11月', '10月', '09月', '08月', '07月', '06月', '05月', '04月', '03月', '02月', '01月'];
    const __formatMonth = 'yyyy年MM月';
    // const __formatDay = 'yyyy年MM月dd日';
    const resultMonth = [];
    let result = [];
    for (let i = 0; i < monthOfYear.length; i++) {
      result = [];
      const item = monthOfYear[i];
      for (let j = 0; j < TaskLists.length; j++) {
        const row = TaskLists[j];
        const __createTimeMonth = Utility.$convertToDateByTimestamp(row.createTime, __formatMonth) + '';
        const month = __createTimeMonth.slice(-3);
        if (item === month) {
          result.push(row);
        }
        // break;
      }
      if (result.length !== 0) {
        resultMonth.push(result);
      }
    }
    // console.log(resultMonth);
    if (!Utility.isArray(resultMonth)) {
      return;
    }
    this.setState({ TaskLists: resultMonth });
  }

  /**
   * 遍历月份对应的任务列表
   * 
   * @param {any} styles 
   * @returns 
   * @memberof GmessageView
   */
  __TaskListMapHtml(styles) {
    const { TaskLists } = this.state;
    if (!Utility.isArray(TaskLists)) {
      return null;
    }
    return TaskLists.map((list, index) => {
      const listOne = list[0] || [];
      const { createTime } = listOne || {};
      // console.log(createTime);
      return (
        <div className={styles.listItemCss} key={'list_item_' + index}>
          <TaskList TaskLists={list} createTime={createTime} />
        </div>
      );
    });
  }

  /**
   * 筛选--取消事件
   * 
   * @memberof SearchPage
   */
  __HandlerCancel() {
    this.state.IsScreen = false;
    this.__UpdateRender();
  }

  /**
   * 确认事件
   * 
   * @memberof SearchPage
   */
  __HandlerConfirm() {
    const { IsCondition, Type, StatusArr } = this.state;
    this.state.IsScreen = false;
    this.state.IsCondition = !IsCondition;
    this.state.IsFocus = false;
    this.state.CurrentSelectInfo = {};
    // const { searchBar } = this.refs;
    // if (searchBar) {
    //   searchBar.__HandlerClearInputKey();
    // }
    this.__UpdateRender();
    const __params = {};
    __params.type = Type || '';
    __params.status = StatusArr || [];
    this.__InitData(__params, false);
  }


  /**
   * 筛选列表HTML
   * 
   * @param {any} styles 
   * @returns 
   * @memberof SearchPage
   */
  __ScreenCheckBoxHtml(styles) {
    return (
      <div className={styles.screenContainer}>
        <div className={styles.upContainer}>
          <div className={styles.typeContainer}>来源</div>
          <div className={styles.anteCss}>
            {
              this.__AnteHtml(styles)
            }
          </div>
          <div className={styles.typeContainer}>状态</div>
          <div className={styles.checkboxStatusCss}>
            {
              this.__StatusHtml(styles)
            }
          </div>
        </div>
        <div className={styles.confirmContainer}>
          <div className={styles.cancelCss} onClick={this.__HandlerCancel.bind(this)}>取消</div>
          <div className={styles.confirmCss} onClick={this.__HandlerConfirm.bind(this)}>确定</div>
        </div>
        <div className={styles.downContainer}>SearChPage</div>
      </div>
    );
  }

  /**
   * @谁HTml
   * 
   * @param {any} styles 
   * @returns 
   * @memberof SearchPage
   */
  __AnteHtml(styles) {
    const { AnTeList, CurrentSelect } = this.state;
    if (!Utility.isArray(AnTeList)) {
      return null;
    }
    const __IsSelect = (index) => { return index === CurrentSelect ? true : false; };
    return AnTeList.map((item, index) => {
      const { Ante } = item || {};
      return (
        <div className={styles.ante} key={'ante_' + index} onClick={this.__HandlerSelectAnte.bind(this, item, index)}>
          <GxButton Text={Ante} IsSelect={__IsSelect(index)} />
        </div>
      );
    });
  }

  /**
   * 切换-选中@按钮
   * 
   * @param {any} item 
   * @param {any} index 
   * @returns 
   * @memberof SearchPage
   */
  __HandlerSelectAnte(item, index) {
    if (!item) {
      return;
    }
    const { type } = item || {};
    this.state.CurrentSelect = index || 0;
    this.state.Type = type;
    this.state.CurrentSelectInfo = {};

    const __ScreenCondition = [];
    __ScreenCondition[0] = index === 0 ? '我@的' : '@我的';
    this.state.ScreenCondition = __ScreenCondition;
    this.__UpdateRender();
  }

  /**
   * 选中状态集合
   * 
   * @param {any} lis 
   * @param {any} index 
   * @returns 
   * @memberof SearchPage
   */
  __HandlerSelectStatus(lis) {
    if (!lis) {
      this.state.CurrentSelectInfo = {};
      return null;
    }
    const { CurrentSelectInfo } = Object.assign({}, this.state);
    const __ScreenCondition = [];
    __ScreenCondition[0] = this.state.CurrentSelect === 0 ? '我@的' : '@我的';
    const { id } = lis;
    if (CurrentSelectInfo[id]) {
      delete CurrentSelectInfo[id];
    } else {
      CurrentSelectInfo[id] = lis.status;
    }
    const _CurrentSelectInfo = Object.values(CurrentSelectInfo) || [];
    for (const i of _CurrentSelectInfo) {
      let __result = '';
      switch (i) {
        case 'START':
          __result = '未处理';
          __ScreenCondition.push(__result);
          break;
        case 'RECEIVED':
          __result = '进行中';
          __ScreenCondition.push(__result);
          break;
        case 'REFUSE':
          __result = '已拒绝';
          __ScreenCondition.push(__result);
          break;
        case 'FINISHED':
          __result = '已完成';
          __ScreenCondition.push(__result);
          break;
        case 'OVER':
          __result = '已关闭';
          __ScreenCondition.push(__result);
          break;
        default:
          break;
      }
    }
    this.state.StatusArr = _CurrentSelectInfo;
    this.state.ScreenCondition = __ScreenCondition;
    // console.log(this.state.StatusArr);
    this.__UpdateRender();
  }

  /**
   * 状态HTML
   * @param {any} styles 
   * @returns 
   * @memberof SearchPage
   */
  __StatusHtml(styles) {
    const { MainStatus, SubStatus, CurrentSelect, CurrentSelectInfo } = this.state;
    if (!Utility.isArray(MainStatus) || !Utility.isArray(SubStatus)) {
      return null;
    }
    let list = [];
    if (CurrentSelect === 0) {
      list = MainStatus;
    } else {
      list = SubStatus;
    }
    if (!Utility.isArray(list)) {
      return null;
    }
    return list.map((lis, index) => {
      const { title, id } = lis || {};
      return (
        <div className={styles.listContainer} key={'_lis_status' + index} onClick={this.__HandlerSelectStatus.bind(this, lis)}>
          <GxButton Text={title} IsSelect={CurrentSelectInfo[id] ? true : false} />
        </div>
      );
    });
  }

  /**
   * 筛选条件显示HTML
   * 
   * @param {any} styles 
   * @returns 
   * @memberof SearchPage
   */
  __ScreenConditionHTML(styles) {
    const { ScreenCondition } = this.state;
    if (!Utility.isArray(ScreenCondition)) {
      return null;
    }
    return ScreenCondition.map((item, index) => {
      return (
        <div className={styles.screenCondition} key={'screen_condition_' + index}>
          {item + (index !== ScreenCondition.length - 1 ? '、' : '')}
        </div>
      );
    });
  }

  render() {
    const styles = require('./scss/SearchPage.scss');
    const { IsFocus, IsScreen, IsHistory, RefreshComplete, NextDataComplete, IsNotData, IsCondition } = this.state;
    // MarginBottom={20}
    const _tltle = '标签、任务、接收人';
    return (
      <div className={styles.searchPageCss}>
        <div className={styles.searchContainer}>
          <div className={styles.screening} onClick={this.__HandlerScreen.bind(this)}>
            <div className={styles.screen}>筛选</div>
            <div>
              <GxIcon IconType={!!IsScreen ? 'iconDown' : 'iconUpward'} />
            </div>
          </div>
          <div className={styles.search}>
            <GxSearchBar ref="searchBar" IsFocus={!!IsFocus} Title={_tltle} onSearch={this.__HandlerSearch.bind(this)} onCancel={this.__Cancel.bind(this)} />
          </div>
        </div>
        {!!IsCondition &&
          <div className={styles.screenConditionCss}>
            <div className={styles.condition}>筛选条件:</div>
            <div className={styles.rightCondition}>
              {this.__ScreenConditionHTML(styles)}
            </div>
          </div>
        }
        <div className={styles.historyAndScreen}>
          {!!IsHistory ? this.__SearchHistoryHtml(styles) : (!!IsScreen ? this.__ScreenCheckBoxHtml(styles) : '')}
        </div>
        {
          !IsNotData ?
            <div className={styles.searchListContainer}>
              <Refresh Percentage={20} RefreshComplete={RefreshComplete} NextDataComplete={NextDataComplete}
                onNextData={this.__HandlerNextData.bind(this)}
                onRefresh={this.__HandlerRefreshData.bind(this)}>
                <div className={styles.container}>
                  {this.__TaskListMapHtml(styles)}
                </div>
              </Refresh>
            </div> : <div className={styles.tipsCss}>抱歉, 没有找到相关内容!</div>
        }
      </div>
    );
  }
}

